package com.m7788.screen;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.imagemanager.util.CacheService;
import com.imagemanager.util.MediaItem;
import com.imagemanager.util.MediaItemTexture;
import com.imagemanager.util.MediaSet;
import com.m7788.adapter.GridAdapter;
import com.m7788.adapter.GridAdapter.OnGridAdapterChangeListener;
import com.m7788.dao.UploadProDataDaoImpl;
import com.m7788.po.UploadInfo;
import com.m7788.po.UploadProData;
import com.m7788.po.UploadResult;
import com.m7788.util.AppUtil;
import com.m7788.util.AutoLoadListener;
import com.m7788.util.AutoLoadListener.AutoLoadCallBack;
import com.m7788.util.Constant;
import com.m7788.util.DialogUploadFile;
import com.m7788.util.DialogUploadFile.OnChooseFileListener;
import com.m7788.util.HttpService;
import com.m7788.util.ImageUpload;
import com.m7788.view.UmengBaseActivity;
import com.tool.utils.DataUtil;
import com.tool.utils.DateUtil;
import com.tool.utils.LogoutUtil;

public class AlbumScreen extends UmengBaseActivity implements OnClickListener ,OnGridAdapterChangeListener,AutoLoadCallBack  {
	LinearLayout ll_page1,ll_page2;
	GridView gridview;
	ImageView image1;
	Button btn_next,btn_order,btn_left,btn_right,btn_submit_1,btn_submit_2,btn_file,btn_roll,btn_submitSingle_1,btn_submitSingle_2,btn_list,btn_dire;
	TextView tv_file,tv_residue,tv_already,tv_attr1;
	RelativeLayout rl_residue,rl_file;
	MediaItemTexture.Config sThumbnailConfig;
	private ArrayList<MediaItem> itemList;
	private ArrayList<MediaItem> allImage;
	GridAdapter ga;
	boolean flag = false;
	boolean loadFlag = false;
	boolean singleFlag =false;
	Bitmap gbitmap;
	
	private String type;//动作类型
	private String params;//参数集合
	Map<String, String> parmasMap = new HashMap<String, String>();
	private String Oper;//判断来源
	private String wapFrom;
	String gpid,gFolderName,mFilePath;
	int floderNum=0,floderMaxNum=10,residue=0;
	UploadProData proData;
	int canTemp=0;
	int curing=0;
	CommandReceiver cmdReceiver;
	Long gDataId;
	boolean firstFlag = true;
	ImageView iv_pro,iv_pro_big;
	AnimationDrawable animPro,animProBig;
	Button btn_rechoose;
	int pageNo = 0;
	int pageSize = 15;
	
	public Handler handler = new Handler();
	 private class CommandReceiver extends BroadcastReceiver{
	       @Override
	       public void onReceive(Context context, Intent intent) {
	        if(intent.getAction().equals(Constant.ACTION_STOA)){
	        	   Bundle bundle = intent.getExtras();
		    	   int operation = bundle.getInt("operation",-1);
		    	   if(operation==55){//
		    		   ga.clearSelect();
		    		   finish();
		    	   }else  if(operation==2){
//		    		   showBtnList();
		    		   finish();
		    	   }else  if(operation==1){
//		    		   btn_list.setVisibility(View.VISIBLE);  
		    		   finish();
			       }else if(operation == 765){
			    	   	loadFlag = false;
			    	    iv_pro.setVisibility(View.VISIBLE);
						iv_pro_big.setVisibility(View.VISIBLE);
			       }else if(operation == 764){
			    	    animPro.stop();
						animProBig.stop();
						iv_pro.setVisibility(View.GONE);
						iv_pro_big.setVisibility(View.GONE);
						loadFlag = true;
			       }else if(operation == 763){
			    	   DataUtil.showLongToast(AlbumScreen.this, "已到最后一页");
			       }
	                 
	          }
	       }                        
	   }
		//读取所有图片
		private void loadImages(){
			final boolean isCacheReady = CacheService.isCacheReady(false);
			if(isCacheReady){
				allImage = new ArrayList<MediaItem>();
				ArrayList<MediaSet> list  = CacheService.loadMediaSets(  true, false);
				for(MediaSet set:list){
					if(set.isDcim&&set.getItems()!=null){
						for(MediaItem item:set.getItems()){
							allImage.add(item);
//			                 MediaItemTexture mt = new MediaItemTexture(AlbumScreen.this,sThumbnailConfig,item);
//			                 item.mThumbnailBitmap = mt.load();
						}
					}
				}
				
			}
		}
	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.album_screen);
        
        for(String a :CacheService.dcimFolderList){
        	Log.e("path", a);
        }
        
        new FileQueryAsyncTask().execute();
//        CacheService.computeDirtySets(AlbumScreen.this);
//        CacheService.startCache(AlbumScreen.this, true);
        initDBdata();
        initView();
        loadImages();
        ImageUpload.getInstance(AlbumScreen.this).setContext(this);
        cmdReceiver = new CommandReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.ACTION_STOA);
        registerReceiver(cmdReceiver, filter);
	}
	
//	public  int get_pic_num(){
//	// 得到屏幕宽高
//    WindowManager windowManager = getWindowManager();
//    Display display = windowManager.getDefaultDisplay();
//    int frameHeith = display.getHeight() ;
//    int frameWith = display.getWidth() ;
//	}
	
	private void initDBdata(){
    	Oper = AppUtil.getRecord(AlbumScreen.this,Constant.OPERATION);
		type =AppUtil.getRecord(AlbumScreen.this,Constant.TYPE);
		params =AppUtil.getRecord(AlbumScreen.this,Constant.PARAMS);
		gFolderName= Constant.DefaultFileName;
		if(params.length()>0){
			parmasMap = AppUtil.combineHttpParams(params);
			wapFrom= parmasMap.get("type");
			gFolderName= AppUtil.UnicodeToGB2312(parmasMap.get("name"));
		}
	}
	
	
	@Override
	protected void onResume() {
		super.onResume();
		if(firstFlag){
			firstFlag = false;
			initGirdView();
		}
		handler.postDelayed(new Runnable() {  
	        public void run() {  
	       	 animPro.start();
	       	 animProBig.start();
	        }
		}, 50); 
		if("2".equals(type)){
			tv_attr1.setText("商品名称：");
			btn_right.setVisibility(View.GONE);//修改图片时，只能选择单张
		}else{//上传
			if("disk".equals(wapFrom)){
	        	
			}else{
				//仓库隐藏文件夹选择，打开图片数量显示
				rl_residue.setVisibility(View.VISIBLE);
				//隐藏多选按钮
				btn_right.setVisibility(View.GONE);
				//打开编辑
				flag = true;
				btn_submit_1.setVisibility(View.VISIBLE);
				btn_submit_2.setVisibility(View.VISIBLE);
				ga.setMultiple(true);
				tv_attr1.setText("商品名称：");
			}
		}
		
		if(singleFlag){
			returnToMultiple();
		}
		
		
        //仓库则要显示剩余可上传张数
		setResidueImage();
		String orderFlag = AppUtil.getRecord(AlbumScreen.this, Constant.ALBUM_ORDER);
//		if("true".equals(orderFlag)){
//			btn_order.setText("升序");
//		}else{
//			btn_order.setText("降序");
//		}
	}
	
	@Override
	protected void onPause() {
	    
	    super.onPause();
	}
	@Override
	protected void onDestroy() {
//		int count = gridview.getCount();
//	    for (int i = 0; i < count; i++) {
//	    	SquareLayout v = (SquareLayout) gridview.getChildAt(i);
//	    	if(v != null){
//		    	for(int j=0;j<v.getChildCount();j++){
//		    		View cv = v.getChildAt(j);
//		    		cleanupDrawables(cv);
//		    	}
//	    	}
//	    }
		this.unregisterReceiver(cmdReceiver);
//		dbUtil.updateOrAddRecord(Constant.TYPE,"");
    	AppUtil.saveRecord(AlbumScreen.this,Constant.PARAMS,"");
    	
		ImageUpload.getInstance(AlbumScreen.this).releaseContext();
		handler.removeCallbacksAndMessages(null);
		System.gc();
		super.onDestroy();
		
	}
	
	/**
	 * 
	 * 方法名：cleanupDrawables 
	 * 功能：清除giridview的缓存
	 * 参数：
	 * @param view
	 * 创建人：huanghaishui  
	 * 创建时间：2014-1-20
	 */
	protected static void cleanupDrawables(View view)
	{
	    cleanupDrawable(view.getBackground());

	    if (view instanceof ImageView)
	        cleanupDrawable(((ImageView)view).getDrawable());
	    else if (view instanceof TextView)
	    {
	        TextView tv = (TextView)view;
	        Drawable[] compounds = tv.getCompoundDrawables();
	        for (int i = 0; i < compounds.length; i++)
	            cleanupDrawable(compounds[i]);
	    }
	    else if (view instanceof ViewGroup && !(view instanceof AdapterView))
	    {
	        ViewGroup vg = (ViewGroup)view;
	        for (int i = 0; i < vg.getChildCount(); i++)
	            cleanupDrawables(vg.getChildAt(i));
	        vg.removeAllViews();
	    }
	}

	protected static void cleanupDrawable(Drawable d)
	{
	    if (d == null)
	        return;

	    d.setCallback(null);

	    if (d instanceof BitmapDrawable){
	        ((BitmapDrawable)d).getBitmap().recycle();
//	        d = null;
	    }
	    else if (d instanceof LayerDrawable)
	    {
	        LayerDrawable layers = (LayerDrawable)d;
	        for (int i = 0; i < layers.getNumberOfLayers(); i++)
	            cleanupDrawable(layers.getDrawable(i));
	    }
	}
	/**
	 * 
	 * 方法名：setResidueImage 
	 * 功能：仓库，设置照片提示
	 * 参数：
	 * 创建人：huanghaishui  
	 * 创建时间：2013-9-12
	 */
	private void setResidueImage(){
		if("1".equals(type)&&!"disk".equals(wapFrom)){
			String fnum = parmasMap.get("num");
			String fmax = parmasMap.get("max_num");
			if(fnum!=null && fmax!=null){
				int re = Integer.valueOf(fmax)-Integer.valueOf(fnum);
				if(re>-1){
					tv_residue.setText("可再传："+re+"张");
				}
				tv_already.setText("已传："+fnum+"张");
				tv_file.setText(gFolderName);
			}
		}
	}
	
	/**
	 * 
	 * 方法名：showBtnList 
	 * 功能：展示上传列表
	 * 参数：
	 * 创建人：huanghaishui  
	 * 创建时间：2013-9-11
	 */
	private void showBtnList(){
//		if(AppUtil.isUploadList(this)){
//			btn_list.setVisibility(View.VISIBLE);
//		}else{
//			btn_list.setVisibility(View.GONE);
//		}
	}

	private void initView(){
		iv_pro = (ImageView)findViewById(R.id.as_iv_pro);
    	animPro = (AnimationDrawable) iv_pro.getBackground();
    	iv_pro_big = (ImageView)findViewById(R.id.as_iv_prob);
    	animProBig = (AnimationDrawable) iv_pro_big.getBackground();
    	iv_pro.setVisibility(View.GONE);
    	iv_pro_big.setVisibility(View.GONE);
		ll_page1 = (LinearLayout) findViewById(R.id.as_ll_page1);
		ll_page2 = (LinearLayout) findViewById(R.id.as_ll_page2);
		rl_file = (RelativeLayout) findViewById(R.id.as_ll_file);
		btn_next = (Button) findViewById(R.id.as_btn_next);
		btn_next.setOnClickListener(this);
		image1 = (ImageView) findViewById(R.id.as_iv_single);
		gridview = (GridView) findViewById(R.id.as_gridview);
		tv_file = (TextView) findViewById(R.id.as_tv_file);
		tv_residue = (TextView) findViewById(R.id.as_tv_residue);
		tv_already = (TextView) findViewById(R.id.as_tv_already);
		tv_attr1 = (TextView) findViewById(R.id.as_tv_attr1);
		rl_residue = (RelativeLayout) findViewById(R.id.as_rl_residue); 
		btn_left = (Button) findViewById(R.id.as_btn_left);
		btn_left.setOnClickListener(this);
		btn_left.setVisibility(View.VISIBLE);
		btn_file = (Button) findViewById(R.id.as_btn_file);
		btn_file.setOnClickListener(this);
		btn_right = (Button) findViewById(R.id.as_btn_right);
		btn_right.setOnClickListener(this);
		btn_submit_1 = (Button) findViewById(R.id.as_btn_submit_1);
		btn_submit_1.setOnClickListener(this);
		btn_submit_2 = (Button) findViewById(R.id.as_btn_submit_2);
		btn_submit_2.setOnClickListener(this);
		
		btn_dire = (Button) findViewById(R.id.as_btn_directory);
		btn_dire.setOnClickListener(this);
		
		btn_order = (Button) findViewById(R.id.as_btn_order);
		btn_order.setOnClickListener(this);
		btn_roll = (Button) findViewById(R.id.as_btn_roll);
		btn_roll.setOnClickListener(this);
		btn_list = (Button) findViewById(R.id.as_btn_list);
		btn_list.setOnClickListener(this);
//		btn_submitSingle_1 = (Button) findViewById(R.id.as_btn_submitSingle_1);
//		btn_submitSingle_1.setOnClickListener(this);
		btn_submitSingle_2 = (Button) findViewById(R.id.as_btn_submitSingle_2);
		btn_submitSingle_2.setOnClickListener(this);
		
		btn_rechoose = (Button) findViewById(R.id.as_btn_rechoose);
		btn_rechoose.setOnClickListener(this);
		
	    sThumbnailConfig = new MediaItemTexture.Config();
   	 	sThumbnailConfig.thumbnailWidth = 128;
        sThumbnailConfig.thumbnailHeight = 96;
        btn_file.setVisibility(View.GONE);
        tv_file.setText(gFolderName);
	}
	private void initGirdView(){
		  itemList = new ArrayList<MediaItem> ();
		  ga = new GridAdapter(this,itemList);
		  gridview.setAdapter(ga);  
	      gridview.setOnItemClickListener(new ItemClickListener());
	      gridview.setOnScrollListener(new AutoLoadListener(this));
	      new LoadImagesTask().execute();
	}
	
	 class  ItemClickListener implements OnItemClickListener  
	  {  
		 public void onItemClick(AdapterView<?> arg0,//The AdapterView where the click happened   
	                                  View arg1,//The view within the AdapterView that was clicked  
	                                  int position,//The position of the view in the adapter  
	                                  long arg3//The row id of the item that was clicked  
	                                  ) {  
			 if(!loadFlag){
				 DataUtil.showShortToast(AlbumScreen.this, "图片还未加载完毕");
				 return;
			 }
			 MediaItem item = (MediaItem) arg0.getItemAtPosition(position);
			 if(flag){
				 if(params.length()>0&&"1".equals(type)){
					 	ArrayList<String> pathList = ga.getSelectItemList();
						parmasMap = AppUtil.combineHttpParams(params);
						String fnum = parmasMap.get("num");
						String fmax = parmasMap.get("max_num");
						String name = AppUtil.UnicodeToGB2312(parmasMap.get("name"));
						if(fnum!=null && fmax!=null){
							int re = Integer.valueOf(fmax)-Integer.valueOf(fnum)-canTemp;
							if(!item.isCheck){
								if(re==0){
									DataUtil.showShortToast(getApplicationContext(), "文件夹："+name+"图片数量已满，无法上传");
									return;
								}
								if(pathList.size()>=re){
									DataUtil.showShortToast(getApplicationContext(), "文件夹："+name+"图片容量剩余"+re+"张,您已选择"+pathList.size()+"张。");
									return;
								}
								re=re-pathList.size()-1;
							}else{
								re=re-pathList.size()+1;
							}
							
//							tv_residue.setText("剩："+re);
							tv_residue.setText("可再传："+re+"张");
						}
					}
					ga.changeDate(position); 
			 }else{
				 ll_page1.setVisibility(View.GONE);
				 ll_page2.setVisibility(View.VISIBLE);
				 btn_right.setVisibility(View.GONE);
				 
				 
				 
				 
				 singleFlag = true;
				 mFilePath= item.mFilePath;
				 int maxSize=0;
				 //Bitmap temp = ImageUpload.readBitmapFromPath(item.mFilePath);
				// gbitmap = AppUtil.rotate(temp, item.mRotation);
				 
				 float degree = AppUtil.readPictureDegree(mFilePath); 
					
					String maxTemp = parmasMap.get("maxsize");
					if(maxTemp!=null&& maxTemp.length()>0){
						maxSize = Integer.valueOf(maxTemp);
					}
					
				gbitmap = ImageUpload.getInstance(AlbumScreen.this).readFromPath(mFilePath,degree,maxSize);
				 
				 image1.setBackgroundDrawable(new BitmapDrawable(gbitmap));
				 //相册单张修改
				 
				 
//				 AppUtil.saveRecord(AlbumScreen.this, Constant.SinglePhoto, item.mFilePath);
//				 AppUtil.saveRecord(AlbumScreen.this, Constant.FLAG, 3+"");
//				 ga.clearMemory();
//				 Intent intent = new Intent(AlbumScreen.this, SinglePhotoScreen.class);
//				 intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//				 startActivity(intent);
//				 
//				 finish();
			 }
		    
		 } 
		 
	 }	 
		 
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.as_btn_next:
			pageNo++;
			new LoadImagesTask().execute();
		break;
		case R.id.as_btn_rechoose:
    		
//  		  DataUtil.deleFileInFolder(ImageUpload.getInstance(AlbumScreen.this.getApplicationContext()).getFileDir());
  		
	  		if(singleFlag){
	  				ll_page1.setVisibility(View.VISIBLE);
					ll_page2.setVisibility(View.GONE);
					singleFlag = false;
	  		}
	  		break;
	    	case R.id.as_btn_left:
	    		
//	    		  DataUtil.deleFileInFolder(ImageUpload.getInstance(AlbumScreen.this.getApplicationContext()).getFileDir());
	    		
//	    		if(singleFlag){
//	    			ll_page1.setVisibility(View.VISIBLE);
//					ll_page2.setVisibility(View.GONE);
//					
//					if("disk".equals(wapFrom)){
//						btn_right.setVisibility(View.VISIBLE);
//					}
//					singleFlag = false;
//	    		}else{
	    			finish();
//	    		}
	    		break;
	    	case R.id.as_btn_right:
	    		if(loadFlag){
		    		if(flag){
		    			flag = false;//关闭编辑
		    			btn_right.setText("多选");
		    			btn_right.setTextColor(Color.WHITE);
		    			
		    			btn_submit_1.setVisibility(View.GONE);		    			
		    			btn_submit_2.setVisibility(View.GONE);
		    			
		    			ga.setMultiple(false);
		    			setResidueImage();
		    			ga.clearSelect();
		    		}else{
		    			flag = true;//打开编辑
		    			btn_right.setText("取消");
		    			btn_right.setTextColor(Color.RED);
		    			
		    			btn_submit_1.setVisibility(View.VISIBLE);
		    			btn_submit_2.setVisibility(View.VISIBLE);
		    			
		    			ga.setMultiple(true);
		    		}
	    		}else{
	    			DataUtil.showShortToast(AlbumScreen.this, "图片还未加载完毕");
	    		}
	    		break;
	    	case R.id.as_btn_submit_1://逆序上传
	    		
	    		update(2);							
				//finish();
	    		break;
	    	case R.id.as_btn_submit_2://顺序上传
	    		
	    		update(1);				
				//finish();
	    		break;
	    	case R.id.as_btn_roll:
	    		if(gbitmap!=null){
					gbitmap = AppUtil.rotate(gbitmap,90);
					image1.setBackgroundDrawable(new BitmapDrawable(gbitmap));
				}
	    		break;
//	    	case R.id.as_btn_submitSingle_1://普清单张图片上传
//	    		update_single(2);	    		
//	    		break;
	    	case R.id.as_btn_submitSingle_2://高清单张图片上传
	    		update_single();	    		
	    		break;
	    	case R.id.as_btn_file:
	    		DialogUploadFile duf = new DialogUploadFile(AlbumScreen.this,new OnChooseFileListener(){

					@Override
					public void setUploadFile(String path,String pid) {
						tv_file.setText(path);
						gFolderName= path;
						gpid = pid;
					}});
	    		duf.show();
	    		break;
	    	case R.id.as_btn_list:
	    		Intent intent2 = new Intent(AlbumScreen.this, UploadInfoScreen.class);
				startActivity(intent2);
	    		break;
	    	case R.id.as_btn_order:
	    		String orderFlag = AppUtil.getRecord(AlbumScreen.this, Constant.ALBUM_ORDER);
	    		if("true".equals(orderFlag)){
	    			AppUtil.saveRecord(AlbumScreen.this, Constant.ALBUM_ORDER,"false");
//	    			btn_order.setText("降序");
	    			CacheService.setImageOrderAsc(true);
	    		}else{
	    			AppUtil.saveRecord(AlbumScreen.this, Constant.ALBUM_ORDER,"true");
//	    			btn_order.setText("升序");
	    			CacheService.setImageOrderAsc(false);
	    		}
	    		CacheService.computeDirtySets(AlbumScreen.this);
	    		CacheService.startCache(AlbumScreen.this, true);
	    		//DataUtil.showLongToast(AlbumScreen.this, "更改相册排序，将在下次启动后生效");
	    		
	    		AlbumScreen_sort_change();
	    		
	    		
	    		
//	    		new LoadImagesTask().execute();
	    		break;
	    	case R.id.as_btn_directory://更改目录
	    		Intent intent3 = new Intent(AlbumScreen.this, DirectoryScreen.class);
				startActivity(intent3);
	    		break;
		}
	}
	
	public void AlbumScreen_sort_change() {
		
		Dialog dialog = new AlertDialog.Builder(AlbumScreen.this)
        .setTitle("更改相册排序，将在下次启动后生效，是否退出？")   
        .setPositiveButton("确定",
                new DialogInterface.OnClickListener() {   
                    @Override   
                    public void onClick(DialogInterface dialog,   
                            int which) {   
//                    	deleHistory();
                    	dialog.dismiss();
                    	finish();
                    	LogoutUtil.getInstance().exit();
                    }   
                }).setNegativeButton("取消",    
                new DialogInterface.OnClickListener() {   
                    public void onClick(DialogInterface dialog,   
                            int whichButton) {   
                    	dialog.dismiss();
                    	finish();
                    }   
                }).create();

			dialog.show(); 
	}
	
	//多张上传
	@SuppressWarnings("unchecked")
	private void update(int sort_flag){
		 AppUtil.saveRecord(AlbumScreen.this, "sort_flag", sort_flag+"");
		ArrayList<String> pathList = ga.getSelectItemList();
	
		if(pathList.size()<1){
			DataUtil.showShortToast(AlbumScreen.this, "请先选择图片");
			btn_submit_1.setClickable(true);
			btn_submit_2.setClickable(true);
			return;
		}
		
		if(params.length()>0&&"1".equals(type)){
			parmasMap = AppUtil.combineHttpParams(params);
			String fnum = parmasMap.get("num");
			String fmax = parmasMap.get("max_num");
			wapFrom= parmasMap.get("type");
			
			if(fnum!=null && fmax!=null){
				int re = Integer.valueOf(fmax)-Integer.valueOf(fnum)-canTemp;
				if(re==0){
					DataUtil.showShortToast(getApplicationContext(), "文件夹："+gFolderName+"图片数量已满，无法上传");
					btn_submit_1.setClickable(true);
					btn_submit_2.setClickable(true);
					return;
				}
				if(pathList.size()>re){
					DataUtil.showShortToast(getApplicationContext(), "文件夹："+gFolderName+"图片容量剩余"+re+"张,您已选择"+pathList.size()+"张。");
					btn_submit_1.setClickable(true);
					btn_submit_2.setClickable(true);
					return;
				}
			}
		}
		proData = new UploadProData();
		UploadProDataDaoImpl daoImpl= new UploadProDataDaoImpl(AlbumScreen.this);
		proData.setTotal(pathList.size());
		proData.setDate(DateUtil.formatDateTimeByDate(new Date()));
		proData.setCur(0);
		proData.setFailNum(0);
		if("2".equals(type)){
			proData.setType("修改");
		}else{
			proData.setType("上传");
		}
		proData.setFileName(gFolderName);
		gDataId= daoImpl.insert(proData);
		new UploadAsyncTask().execute(gDataId);
		
		Intent intent = new Intent(AlbumScreen.this, UploadInfoScreen.class);
		startActivity(intent);
		
		finish();
		//按纽屏蔽
		btn_submit_1.setClickable(false);
		btn_submit_2.setClickable(false);
	}
	
	
	
	
	
	
	//相册单张上传
	private void update_single(){
//		AppUtil.saveRecord(AlbumScreen.this, "this_flag", this_flag+"");
		
		int maxSize=0;
		proData = new UploadProData();
		UploadProDataDaoImpl daoImpl2= new UploadProDataDaoImpl(AlbumScreen.this);
		ArrayList<UploadInfo> infoList = new ArrayList<UploadInfo>();
		if("2".equals(Oper)&&gbitmap!=null){
			String id = AppUtil.getRecord(AlbumScreen.this,Constant.sid);
			String pid = AppUtil.getRecord(AlbumScreen.this,Constant.Tpid);
			if(gpid!=null){//有选择文件夹，则使用选择的
				pid=gpid;
			}
			String url = AppUtil.getRecord(AlbumScreen.this,Constant.URL_UPLOAD);
			parmasMap.put("id", id);
			parmasMap.put("p_id", pid);
			parmasMap.put("url", url);
			parmasMap.put("name", Constant.DefaultFileName);
			if(gFolderName!=null){
				parmasMap.put("name", gFolderName);
			}
		}else  if("1".equals(Oper) && params.length()>0){//来自网络
				parmasMap = AppUtil.combineHttpParams(params);
				String fnum = parmasMap.get("num");
				String fmax = parmasMap.get("max_num");
				wapFrom= parmasMap.get("type");
				String name = AppUtil.UnicodeToGB2312(parmasMap.get("name"));
				String maxTemp = parmasMap.get("maxsize");
				if(maxTemp!=null&& maxTemp.length()>0){
					maxSize = Integer.valueOf(maxTemp);
				}
				if(fnum!=null && fmax!=null){
					int re = Integer.valueOf(fmax)-Integer.valueOf(fnum)-canTemp;
					if(re==0){
						DataUtil.showShortToast(getApplicationContext(), "文件夹："+name+"图片数量已满，无法上传");
//						btn_submitSingle_1.setClickable(true);
						btn_submitSingle_2.setClickable(true);
						return;
					}
				}
				
				String cuurimg=parmasMap.get("cuurimg");
				if(cuurimg!=null && cuurimg.length()>0){
					int temp = Integer.valueOf(cuurimg);
					temp=temp+1+curing;
					parmasMap.put("cuurimg", temp+"");
				}
		}
		String name = mFilePath.substring(mFilePath.lastIndexOf(File.separator)+1,mFilePath.lastIndexOf("."));
		parmasMap.put("fName", name);
//		Log.e("相册上传图片长宽",gbitmap.getHeight()+"--"+gbitmap.getWidth());
		File file = ImageUpload.getInstance(AlbumScreen.this).formatFileFromBitmap(gbitmap,maxSize);
		File sfile = ImageUpload.getInstance(AlbumScreen.this).formatFileFromBitmapSmall(gbitmap);
		
//		File file = ImageUpload.getInstance().readFromUri(mFilePath,0,maxSize);
//		File sfile = ImageUpload.getInstance().readFromUriSmall(mFilePath,0);
//		
		UploadInfo info = new UploadInfo();
		info.setParmasMap(parmasMap);
		info.setFile(file);
		info.setSmallFile(sfile);
		infoList.add(info);
		curing++;
		proData.setInfoList(infoList);
		proData.setTotal(infoList.size());
		proData.setDate(DateUtil.formatDateTimeByDate(new Date()));
		proData.setCur(0);
		proData.setFailNum(0);
		proData.setFileName(AppUtil.UnicodeToGB2312(parmasMap.get("name")));
		if("2".equals(type)){
			proData.setType("修改");
		}else{
			proData.setType("上传");
		}
		gDataId= daoImpl2.insert(proData);
		sendImage();
		canTemp++;
		
		Intent intent3 = new Intent(AlbumScreen.this, UploadInfoScreen.class);
		startActivity(intent3);
//		returnToMultiple();
		if(wapFrom!=null){
			finish();
		}
		//按纽屏蔽
//		btn_submitSingle_1.setClickable(false);
		btn_submitSingle_2.setClickable(false);

	}
	
	class LoadImagesTask extends AsyncTask <Object, MediaItem, Object>{

		@Override
		protected Object doInBackground(Object... params) {
			AppUtil.sendMesToActivity(AlbumScreen.this, 765, "");
			if(allImage.size()>0){
				int start = 0 + pageNo * pageSize;
				int end = (1 + pageNo) * pageSize;
				if(end > allImage.size()){
					end = allImage.size();
				}
				if(start<allImage.size()){
					for(int i=start;i<end;i++){
						MediaItem item = allImage.get(i);
						MediaItemTexture mt = new MediaItemTexture(AlbumScreen.this,sThumbnailConfig,item);
		                 item.mThumbnailBitmap = mt.load();
		                 publishProgress(item);
					}
				}else{
					AppUtil.sendMesToActivity(AlbumScreen.this, 763, "");
				}
			}
				
			return null;
		}
		@Override
		public void onProgressUpdate(MediaItem... value) {
			for (MediaItem item : value) {
				ga.addItem(item);
				ga.notifyDataSetChanged();
			}
		}
		@Override
		protected void onPostExecute(Object result) {
			
			AppUtil.sendMesToActivity(AlbumScreen.this, 764, "");
		}
	}

	@Override
	public void changeAdapterDate(int currentItem) {
		ga.notifyDataSetChanged();
	}

	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK && singleFlag){
			returnToMultiple();
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	/**
	 * 
	 * 方法名：returnToMultiple 
	 * 功能：返回多选界面
	 * 参数：
	 * 创建人：huanghaishui  
	 * 创建时间：2013-9-10
	 */
	private void returnToMultiple(){
		ll_page1.setVisibility(View.VISIBLE);
		ll_page2.setVisibility(View.GONE);
		btn_right.setVisibility(View.VISIBLE);
		singleFlag = false;
	}

	@SuppressWarnings("rawtypes")
	private class FileQueryAsyncTask extends AsyncTask {
		@SuppressWarnings("unchecked")
		@Override
		protected void onPostExecute(Object result) {
//			progressDialog.dismiss();
			if (result != null&&result.toString().length()>0) {
				  String json = result.toString();
				  AppUtil.saveRecord(AlbumScreen.this, "fileJson", json);
			} else {
			}
			super.onPostExecute(result);
		}

		@Override
		protected Object doInBackground(Object... params) {
			return HttpService.getInstance(AlbumScreen.this).getPathList();

		}
	}
	@SuppressWarnings("rawtypes")
	private class UploadAsyncTask extends AsyncTask {
		@Override
		protected void onPostExecute(Object result) {
			super.onPostExecute(result);
			
			if(wapFrom!=null){
				finish();
			}
		}

		@Override
	 protected Object doInBackground(Object... oparams) {
			int maxSize=0;
			ArrayList<UploadInfo> infoList = new ArrayList<UploadInfo>();    					
			ArrayList<String> pathList = ga.getSelectItemList();			
					
			
			//逆序上传
			String sort_flag=AppUtil.getRecord(AlbumScreen.this, "sort_flag");	
			if("2".equals(sort_flag)){			
				ArrayList<String> list2 = new ArrayList<String>();		
				int size = pathList.size()-1;
				for(int i = size;i>=0;i--){
					list2.add(pathList.get(i));
				}
				pathList=list2;
			}		
			
			ArrayList<Float> rotationList =ga.getSelectItemRotationList();
    		
    		Intent intent = new Intent();
  		    intent.putExtra("operation", 55);
  		    intent.setAction(Constant.ACTION_STOA);
  		    AlbumScreen.this.sendBroadcast(intent);  
    		
    		canTemp += pathList.size();
    		
    		//处理图片
    		for(int m=0;m<pathList.size();m++){
    			
    			String tempPath = pathList.get(m);
    			if("2".equals(Oper)){
					String id = AppUtil.getRecord(AlbumScreen.this,Constant.sid);
					String pid = AppUtil.getRecord(AlbumScreen.this,Constant.Tpid);
					if(gpid!=null){//有选择文件夹，则使用选择的
						pid=gpid;
					}
					String url = AppUtil.getRecord(AlbumScreen.this,Constant.URL_UPLOAD);
					parmasMap = new HashMap<String, String>();
					parmasMap.put("id", id);
					parmasMap.put("p_id", pid);
					parmasMap.put("url", url);
					//本地批量上传才有文件夹选择
					parmasMap.put("name", Constant.DefaultFileName);
					if(gFolderName!=null){
						parmasMap.put("name", gFolderName);
					}
				}else{
					if(params.length()>0){
						parmasMap = AppUtil.combineHttpParams(params);
						String cuurimg=parmasMap.get("cuurimg");
						String maxTemp = parmasMap.get("maxsize");
//						String this_flag = dbUtil.getRecord("this_flag");
						
						if(maxTemp!=null&& maxTemp.length()>0){
							maxSize = Integer.valueOf(maxTemp);
							//Integer.valueOf(this_flag);
						}
						
						if(cuurimg!=null && cuurimg.length()>0){
							int temp = Integer.valueOf(cuurimg);
							temp=temp+1+curing;
							parmasMap.put("cuurimg", temp+"");
						}
					}
				}
	    		String name = tempPath.substring(tempPath.lastIndexOf(File.separator)+1,tempPath.lastIndexOf("."));
				parmasMap.put("fName", name);
				File file = ImageUpload.getInstance(AlbumScreen.this).readFromUri(tempPath,AppUtil.readPictureDegree(tempPath),maxSize);
				File sfile = ImageUpload.getInstance(AlbumScreen.this).readFromUriSmall(tempPath,AppUtil.readPictureDegree(tempPath));
				
				UploadInfo info = new UploadInfo();
				info.setParmasMap(parmasMap);
				info.setFile(file);
				info.setSmallFile(sfile);
				infoList.add(info);
				curing++;
    		}
    		proData.setInfoList(infoList);
    		
    		
    		
    		sendImage();
			return null;
	 }
	}

	    private  void sendImage(){
	    	Thread t = new Thread() {
				@Override
				public void run() {
					UploadProDataDaoImpl daoImpl = new UploadProDataDaoImpl(AlbumScreen.this);
					boolean isCancle = false;
					boolean isFail = false;
					Long id;
					if(gDataId==0){
						id = daoImpl.insert(proData);
					}else{
						id=gDataId;
					}
					AppUtil.sendMesToActivity(AlbumScreen.this,1,"");
					ArrayList<UploadInfo> list = proData.getInfoList();
					int j=0;
					int fail=0;
					for(int i=0;i<list.size();i++){
						j++;
						
						UploadProData temp = daoImpl.get(id.intValue());
						if(temp==null){
							isCancle =true;
							break;
						}
						//防止数据库锁，暂停
						try {
							sleep(100);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						
						UploadInfo info = list.get(i);
						if(temp.getFlag()==1){
							break;
						}else{
							String result = HttpService.getInstance(AlbumScreen.this).uploadPicture(info);
							UploadResult re=getResult(result);
							if(re.ok){
								temp.setCur(j);
							}else{//失败
								try {
									sleep(1500);
								} catch (InterruptedException e) {
									e.printStackTrace();
								}
								String result2 = HttpService.getInstance(AlbumScreen.this).uploadPicture(info);
								UploadResult re2=getResult(result2);
								if(re2.ok){
									temp.setCur(j);
								}else{
									fail++;
									isFail = true;
									temp.setRemark(re.desc);
									AppUtil.sendMesToActivity(AlbumScreen.this,3,re.desc);
								}
								
							}
							temp.setFailNum(fail);
							
							daoImpl.update(temp);
							//防止数据库锁，暂停
							try {
								sleep(100);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
							AppUtil.sendMesToActivity(AlbumScreen.this,1,"");
						}
						
					}
					proData = null;
					gDataId = null;
					if(!isCancle){
						//上传循环结束，若记录不是中断记录，则删除
						if(!isFail){
							try {
								sleep(100);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
							AppUtil.saveRecord(AlbumScreen.this, "fabu", "true");
							
							AppUtil.sendMesToActivity(AlbumScreen.this,2,"上传成功");
						}
						
					}else{
						
					}
				}
	    		
	    	};
	    	t.start();
	    }
	    
	    private static UploadResult getResult(String result){
	    	UploadResult re = new UploadResult();
	    	if(result==null){
	    		re.ok= false;
	    		re.desc="网络异常，上传失败";
	    		return re;
	    	}
	    	//正式
	    	String json = result.toString();
			  try {
				String ret = new JSONObject(json).getString("ret");
				if("0".equals(ret)){
					re.ok= false;
				
				} else if("1".equals(ret)){
					String code = new JSONObject(json).getString("result");
					String desc = new JSONObject(json).getString("desc");
					if("0".equals(code)){
						re.ok= false;
						re.desc = desc;
					}else if("1".equals(code)){
						//成功
					}else if("2".equals(code)){
						re.ok= false;
						re.desc = desc;
					}
					
				}
			} catch (JSONException e) {
				e.printStackTrace();
				re.ok= false;
				re.desc="网络异常，上传失败";
				return re;
			}
			return re;
	    }
		@Override
		public void loadMore() {
			pageNo++;
			new LoadImagesTask().execute();
		}
}



